package com.spring.boot.autoconfigure;

import com.context.DynamicRDBContext;
import com.util.RDBUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.util.Map;

/**
 * spring-data-redis 动态数据源核心自动配置类
 *
 * @author wanghaicheng
 * @since 1.0.0
 */
@Slf4j
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(RDBProperties.class)
@AutoConfigureBefore(RedisAutoConfiguration.class)
@ConditionalOnProperty(prefix = RDBProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class DynamicRDBAutoConfiguration {

    private final RDBProperties rdbProperties;

    @Bean
    public DynamicRDBContext dynamicRDBContext() {
        log.debug("初始化redis连接工厂");
        DynamicRDBContext dynamicRDBContext = new DynamicRDBContext();
        Map<String, RedisConnectionFactory> factories = DynamicRDBContext.getRedisConnectionFactories();
        Map<String, RDBProperty> dynamic = rdbProperties.getDynamic();
        dynamic.forEach((k, v) -> factories.put(k, RDBUtil.connectionFactory(v.getIndex(), v.getHost(), v.getPort(), v.getPassword())));
        return dynamicRDBContext;
    }
}
